import 'dart:async';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/config/app_data_cache.dart';
import 'package:app/src/http/model/app_model.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/banner.dart';
import 'package:app/src/http/bean/ywx_count.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/http/model/banner_model.dart';
import 'package:app/src/http/model/ywx_model.dart';
import 'package:app/src/manager/ywx_manager.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/popuwindow/popuwindow_used.dart';
import 'package:app/src/utils/image_path_utils.dart';
import '../../../../config/app_data_config.dart';
import '../../../../http/bean/user.dart';
import '../../../../http/model/todo_review_model.dart';
import '../../../../http/model/user_model.dart';
import '../../../../manager/audit_manager.dart';
import '../../../../manager/user_manager.dart';
import '../../helper/route_helper.dart';
import '../user/user.dart';

///主页
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  _HomePagePrenster presenter = _HomePagePrenster();

  @override
  void initState() {
    presenter._homePageState = this;
    //版本更新检测
    presenter?.checkUpdate(context);
    //获取通知栏信息
    presenter?.getcompanynotice(context);
    //获取未审核个数
    presenter?.getYwxCount(context);
    //获取用户信息
    presenter?.getpersoninfo(context, (value) {
      setState(() {});
    });
    AuditManager.getAuditManager()
        .setDetailsWithAuto(false, "home.dart"); //fixme 不在审核详情页面;
  }

  String? _title = null; //标题
  TextStyle? _titleTextSyle = null;

  @override
  Widget build(BuildContext context) {
    //AuditManager.setDetailsWithAuto(false,"home.dart"); //fixme 不在审核详情页面;这里不要调用；因为这里刷卡接口会实时刷新这个页面。
    List<CompanyNoticeInfo>? datas = presenter.companyNoticeInfo;
    _title = null;
    try {
      if (datas != null && datas.length > 0 && initialPage < datas.length) {
        String? NoticeTitle = datas[initialPage].NoticeTitle;
        if (!StringUtils.isEmpty(NoticeTitle)) {
          _title = NoticeTitle;
          String? ThemeColor = datas[initialPage].ThemeColor;
          if (StringUtils.isEmpty(ThemeColor)) {
            ThemeColor = "FFFFFF";
          }
          String? FontSize = datas[initialPage].FontSize?.trim();
          if (!StringUtils.isEmpty(FontSize)) {
            //print("FontSize:$FontSize");
            double pxFontSize = double.parse(FontSize!);
            if (pxFontSize > 45) {
              pxFontSize = 45;
            }
            if (pxFontSize < 10) {
              pxFontSize = 10;
            }
            _titleTextSyle = TextStyle(
                color: ColorUtils.parseColor(ThemeColor), fontSize: pxFontSize);
          } else {
            _titleTextSyle =
                TextStyle(color: ColorUtils.parseColor(ThemeColor));
          }
        }
      }
    } catch (e) {
      print("首页ViewPage标题字体和颜色设置异常：$e");
    }
    if (StringUtils.isEmpty(_title)) {
      _title = AppStrings.of(context).bwg;
      _titleTextSyle = TextStyle(color: Colors.white);
    }
    px.init(context);
    pageViewHeight = px.screenWidth() / (1080 / 300);
    if (pageViewHeight < 200) {
      pageViewHeight = 200;
    }
    //所有功能
    List<YwxItem> allItems = YwxIdManager.getNoUsedItems(context);
    //常用功能
    List<YwxItem> items = YwxIdManager.getUsedItems(context);
    return Stack(
      children: [
        Container(
          color: AppColors.backgroundColorWithWhite,
          child: CustomScrollView(
            physics: BouncingScrollPhysics(),
            slivers: [
              MediaQuery.removePadding(
                //removeBottom: true,
                //removeTop: true,
                context: context,
                child: SliverAppBar(
                  //systemOverlayStyle: setStatusBarColor(WhiteFont: true),
                  automaticallyImplyLeading: false,
                  //automaticallyImplyLeading true 当Scaffold具备drawer左菜单时，自动给leading添加菜单图标。
                  pinned: true,
                  //pinned 意为固定；true 标题栏估计不会滑走；false 不固定，标题栏和内容一起滑动。
                  expandedHeight: pageViewHeight - px.statusBarHeight(),
                  //toolbarHeight: 0,
                  backgroundColor: Colors.blueAccent,
                  title: Text(
                    _title!!,
                    style: _titleTextSyle,
                  ),
                  //flexibleSpace 具备Material折叠的风格。;flexibleSpace 英文为 灵活的空间（弹性空间）
                  flexibleSpace: FlexibleSpaceBar(
                    //title: Text(''), //这个title具备上下移动效果。
                    titlePadding: EdgeInsets.only(bottom: 20),
                    centerTitle: true,
                    background: _pageView(),
                  ),
                ),
              ),
              //搜索
              search(context),
              //代办事项
              _todo(context),
              //常用功能
              _usedFunctionsWithTitle(context, items),
              //所有功能
              _allFunctionsWithLine(context, allItems, items),
              _allFunctionsWithTitle(context, allItems),
            ],
          ),
        ),
      ],
    );
  }

  double searchHeight = 40;

  ///搜索
  Widget search(BuildContext context) {
    var inkwell = InkWell(
      onTap: () {
        AppRouteHelper.goSearchRoute(context);
      },
      child: Container(
        color: AppColors.backgroundColorWithWhite,
        padding: EdgeInsets.only(top: 10),
        child: Container(
          margin: AppEdgeInsets.paddingWithItem(),
          padding: AppEdgeInsets.paddingWithItem(),
          height: searchHeight,
          alignment: Alignment.centerLeft,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(searchHeight)),
              border: Border.all(color: Colors.grey, width: 1)),
          child: Row(
            children: [Icon(Icons.search), Text(AppStrings.of(context).search)],
          ),
        ),
      ),
    );
    return MultiSliver(
      pushPinnedChildren: false,
      // false（默认） SliverPersistentHeader头部会固定（不会滑走），true 会滑走。
      children: <Widget>[
        SliverPersistentHeader(
          pinned: true, //true 固定头部，false滑走。
          delegate: StickyChildDelegate(
              child: inkwell,
              maxHeight: searchHeight + 10,
              minHeight: searchHeight + 10),
        ),
      ],
    );
  }

  double pageViewHeight = 200;
  AioPageController? _aioPageController = null;

  Widget _image(String? imageUrl, double width, double height) {
    //print("url============================${imageUrl}");
    // return AppUi.getEmptyView();
    var imagePath = ImagePathUtils.getPathWithImage('ic_bg_home_top.png');
    return FImage(
      imageUrl,
      placeholder: imagePath,
      width: width,
      height: height,
      fit: BoxFit.cover,
      isCache: true,
    );
  }

  int initialPage = 0;

  ///pageView
  Widget _pageView() {
    if (_aioPageController == null) {
      _aioPageController = AioPageController(initialPage: initialPage);
    }
    //print("通知============================${presenter?.companyNoticeInfo}\t${presenter!.companyNoticeInfo!.length}");
    // if (presenter?.companyNoticeInfo == null) {
    //   return LibUi.getCircularProgressIndicator(context);
    // }
    if (presenter?.companyNoticeInfo == null ||
        presenter!.companyNoticeInfo!.length <= 0) {
      return _image(null, px.screenWidth(), pageViewHeight);
    }
    List<CompanyNoticeInfo> datas = presenter.companyNoticeInfo!;
    var pageViewLength = datas.length;
    Widget dotView; //底部小圆点
    if (presenter?.companyNoticeInfo != null &&
        presenter!.companyNoticeInfo!.length >= 1) {
      dotView = Container(
        //width: px.screenWidth(),
        height: pageViewHeight - 10,
        child: Align(
          child: PageIndicator(
            controller: _aioPageController,
            //控制器
            pageCount: pageViewLength,
            //pageView的实际个数（支持无限循环）
            size: 8,
            selectSize: 8,
            isStrip: false,
            isStripWithSelect: true,
            isStroke: true,
            isStrokeWithSelect: false,
            type: MaterialType.circle,
          ),
          alignment: Alignment.bottomCenter,
        ),
      );
    } else {
      dotView = LibUi.getEmptyView();
    }
    return Stack(
      children: [
        Container(
          //width: px.screenWidth(),//默认就是占满父容器全屏，不需要设置
          height: pageViewHeight,
          child: PageView.builder(
            itemBuilder: (context, index) {
              //print("======================================================进来了$index");
              return Container(
                width: px.screenWidth(),
                height: pageViewHeight,
                child: InkWell(
                  child: _image(datas[index].getNoticePictureUrl(),
                      px.screenWidth(), pageViewHeight),
                  onTap: () {
                    //print("================================================点击事件：${datas[index].NoticeTitle}");
                    var title = datas[index].NoticeTitle;
                    var initialData = datas[index].NoticeContent;
                    AppRouteHelper.goWebViewRoute(context,
                        title: title, initialData: initialData);
                  },
                ),
              );
            },
            scrollDirection: Axis.horizontal,
            physics: BouncingScrollPhysics(),
            itemCount: pageViewLength,
            controller: _aioPageController!
              ..periodic(pageViewLength, milliseconds: 4000),
            //4960
            //自带轮播
            onPageChanged: (index) {
              if (mounted) {
                //fixme 全局页面刷新
                setState(() {
                  initialPage = index;
                });
              }
            },
          ),
        ),
        dotView,
      ],
    );
  }

  ///常用功能
  Widget _usedFunctionsWithTitle(BuildContext context, List<YwxItem> items) {
    if (StringUtils.isEmpty(items)) {
      return AppUi.getEmptyViewWithSliver();
    }
    return SliverStickyHeader(
      header: Container(
        color: AppColors.backgroundColorWithWhite,
        padding: AppEdgeInsets.paddingWithItem(top: 16, bottom: 8),
        child: Text(
          AppStrings.of(context).usedFuns,
          style: AppStyle.textStyleWithTitle(),
        ),
      ),
      sliver: _usedFunctionsWithAdapter(context, items),
    );
  }

  Widget _usedFunctionsWithAdapter(BuildContext context, List<YwxItem> items) {
    if (items.length <= 0) {
      return Container(
        height: 0,
      );
    }
    return SliverGrid(
      delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
        var item = items[index];
        return Material(
          color: AppColors.backgroundColorWithWhite,
          child: InkWell(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                AppUi.getBadge(
                    presenter?.ywxCount?.getNum(item.ReviewType),
                    Image.asset(
                      item.ImagePath!,
                      width: 40,
                      height: 40,
                    )),
                Text(
                  item.YwxName!,
                  textAlign: TextAlign.center,
                  style: AppStyle.textStyleWithItem(),
                )
              ],
            ),
            onTap: () {
              item.goWorks(context);
            },
            onLongPress: () {
              //长按删除常用功能
              AppDialog.showDialogWithAlert(context,
                      content: AppStrings.of(context).DelUsed)
                  ?.then((value) {
                if (BoolUtils.isBool(value)) {
                  AppDataCache.removeUsedItems(item.YwxId);
                  presenter?._homePageState?.setState(() {});
                }
              });
            },
          ),
        );
      }, childCount: items.length),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          //crossAxisCount 每行条目个数；
          mainAxisSpacing: 0,
          //mainAxisSpacing 主轴方向之间的间距；
          crossAxisSpacing: 4,
          //crossAxisSpacing 交叉轴方向元素之间的间隙。
          // childAspectRatio: 1.6,
          //childAspectRatio 子元素宽高比
          mainAxisExtent: 100),
    );
  }

  ///所有功能横线
  ///allItems 所有功能
  ///usedItems 常用功能
  Widget _allFunctionsWithLine(
      BuildContext context, List<YwxItem> allItems, List<YwxItem> usedItems) {
    if (StringUtils.isEmpty(allItems) || StringUtils.isEmpty(usedItems)) {
      return AppUi.getEmptyViewWithSliver();
    }
    return SliverToBoxAdapter(
      child: Container(
        color: AppColors.backgroundColorWithGrey,
        //margin: EdgeInsets.only(top: 16),
        height: 8,
      ),
    );
  }

  ///所有功能
  Widget _allFunctionsWithTitle(BuildContext context, List<YwxItem> allItems) {
    if (StringUtils.isEmpty(allItems)) {
      return AppUi.getEmptyViewWithSliver();
    }
    return SliverStickyHeader(
      header: Container(
        color: AppColors.backgroundColorWithWhite,
        padding: AppEdgeInsets.paddingWithItem(top: 8, bottom: 8),
        child: Text(
          AppStrings.of(context).allFuns,
          style: AppStyle.textStyleWithTitle(),
        ),
      ),
      sliver: _allFunctionsWithAdapter(context, allItems),
    );
  }

  Widget _allFunctionsWithAdapter(
      BuildContext context, List<YwxItem> allItems) {
    if (allItems.length <= 0) {
      return Container(
        height: 0,
      );
    }
    return SliverList(
      delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
        var item = allItems[index];
        GlobalKey _globalKeyglobalKey = GlobalKey();
        return Material(
          color: AppColors.backgroundColorWithWhite,
          child: InkWell(
            onTap: () {
              item.goWorks(context);
            },
            child: Container(
              height: 55,
              child: ListTile(
                title: Text(
                  item.YwxName!,
                  style: AppStyle.textStyleWithItem(),
                ),
                leading: AppUi.getBadge(
                    presenter?.ywxCount?.getNum(item.ReviewType),
                    Image.asset(
                      item.ImagePath!,
                      width: 40,
                      height: 40,
                    )),
                contentPadding: EdgeInsets.only(right: 0, bottom: 0, left: 16),
                trailing: InkWell(
                    child: Container(
                      child: Icon(
                        Icons.more_horiz,
                        // Icons.add,
                        key: _globalKeyglobalKey,
                        size: 16,
                        color: ColorUtils.parseColor("#3D3D3D"),
                      ),
                      width: 55,
                      alignment: Alignment.center,
                    ),
                    onTap: () {
                      // showPopuMenuWithUsed(context, _globalKeyglobalKey, item,
                      //     () {
                      //   presenter?._homePageState?.setState(() {});
                      // });
                      //添加到常用功能
                      AppDialog.showDialogWithAlert(context,
                              content: AppStrings.of(context).AddUsed2)
                          ?.then((value) {
                        if (BoolUtils.isBool(value)) {
                          AppDataCache.addUsedItems(item.YwxId);
                          presenter?._homePageState?.setState(() {});
                        }
                      });
                    }),
              ),
            ),
          ),
        );
      }, childCount: allItems.length),
    );
  }

  ///待办事项
  Widget _todo(BuildContext context) {
    // if (allItems.length <= 0) {
    //   return Container(
    //     height: 0,
    //   );
    // }
    // if (StringUtils.isEmpty(items)) {
    //   return AppUi.getEmptyViewWithSliver();
    // }
    var sliverList = SliverList(
      delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
        return Material(
          color: AppColors.backgroundColorWithWhite,
          child: InkWell(
            onTap: () {
              ///跳转到待办事项
              AppRouteHelper.goTodo(context);
            },
            child: Container(
              height: 55,
              child: ListTile(
                title: Text(
                  AppStrings.of(context).ToAudit, //待审核
                  style: AppStyle.textStyleWithItem(),
                ),
                leading: Container(
                  child: AppUi.getBadge(
                      // TodoReviewModel.num, //小圆点数字
                      presenter?.ywxCount?.getAllNum(context, typeName: false),
                      Image.asset(
                        ImagePathUtils.getPathWithImageItem("ic_daiban.png")!,
                        width: 40,
                        height: 40,
                      )),
                  width: 50,
                  height: 50,
                ),
                contentPadding: EdgeInsets.only(right: 16, bottom: 0, left: 16),
                trailing: Container(
                  child: AppUi.getRightGo(),
                  alignment: Alignment.centerRight,
                  width: 55,
                  height: 55,
                ),
              ),
            ),
          ),
        );
      }, childCount: 1),
    );
    return sliverList;

    // return SliverStickyHeader(
    //   header: Container(
    //     color: AppColors.backgroundColorWithWhite,
    //     padding: AppEdgeInsets.paddingWithItem(top: 16, bottom: 8),
    //     child: Text(
    //       AppStrings.of(context).ToAudit,
    //       style: AppStyle.textStyleWithTitle(),
    //     ),
    //   ),
    //   sliver: sliverList,
    // );
  }
}

class _HomePagePrenster {
  _HomePageState? _homePageState;
  List<CompanyNoticeInfo>? companyNoticeInfo = null;

  ///版本更新
  void checkUpdate(BuildContext context) {
    if (PlatformUtils.isAndroid()) {
      AppModel.checkUpdate(context, false);
    }
  }

  ///获取广告位
  void getcompanynotice(BuildContext context) {
    BannerModel.getcompanynotice(context, false, (value) {
      if (_homePageState?.mounted ?? false) {
        if (value.isSuccessForCode()) {
          //刷新页面
          _homePageState?.setState(() {
            companyNoticeInfo = value.Data;
            //print("=======================================通知栏信息${companyNoticeInfo?.length}");
          });
        } else {
          AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
        }
      }
    });
  }

  YwxCount? ywxCount = null;

  Timer? _timer = null;

  ///获取列表显示条目数字（未审核个数）
  void getYwxCount(BuildContext context) {
    //print('计数获取==============================================================0');
    _getYwxCount(context);
    _getTodoReview(context);
    _timer?.cancel();
    _timer = null;
    _timer = Timer.periodic(Duration(milliseconds: 15000), (timer) {
      //print('计数获取==============================================================1:${_homePageState?.mounted}');
      //mounted判断当前StatefulWidget是否显示。
      if (_homePageState?.mounted ?? false) {
        _getYwxCount(context); //审核数字
        _getTodoReview(context); //获取待审核数据
        // UserPresenter?.getpersoninfo(context, (value) {},
        //     isAuto: false,
        //     isAutoLogin: false,
        //     isEnableLoad: false); //获取最新用户信息，仅仅只是获取，不作跳转；fixme 不需要调用。频繁调用了，不好。就直接在首次进入的时候调一次就好了。
      } else {
        //print("=====================================================================进来了");
        _timer?.cancel();
        _timer = null;
        //print('计数获取==============================================================2');
      }
    });
  }

  ///审核小数字
  void _getYwxCount(BuildContext context) {
    YwxModel.getYwxCount(context, false)?.then((value) {
      if (_homePageState?.mounted ?? false) {
        _homePageState?.setState(() {
          ywxCount = value;
        });
      }
    });
  }

  //获取待审核数据
  void _getTodoReview(BuildContext context) {
    //fixme 该方法已经移到main/main.dart主页面去，方便全局实现。
    // TodoReviewModel.getTdogetlist(context, false)?.then((value) {
    //   if (_homePageState?.mounted ?? false) {
    //     _homePageState?.setState(() {});
    //     if (TodoReviewModel.newNotice?.isNew() ?? false) {
    //       TodoReviewModel.newNotice?.showNewDialog(context);
    //     }
    //   }
    // });
  }

  ///获取用户信息;
  void getpersoninfo(
      BuildContext context, ResponseCallbackWithT_<UserInfo> callback) {
    UserPresenter?.getpersoninfo(context, callback,
        isAutoLogin: true, isAuto: true, isEnableLoad: false);
  }
}
